package com.bite.logistics.listener;

import com.bite.logistics.constant.Constants;
import com.bite.order.model.OrderInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = Constants.EXTENSION_DIRECT_QUEUE)
public class ExtensionListener {

    @RabbitHandler
    public void handler1(@Payload String content, Message message, Channel channel) {
        System.out.println("ExtensionListener: " + content);
        Long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                channel.basicReject(deliveryTag, true);
                log.info("消息处理失败，deliveryTag: {}", deliveryTag);
            } catch (IOException ex) {
                log.info("拒绝消息失败，deliveryTag: {}", deliveryTag);
            }
        }
    }

    @RabbitHandler
    public void handler2(@Payload OrderInfo orderInfo, Message message, Channel channel) {
        System.out.println("ExtensionListener: " + orderInfo);
        Long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                channel.basicReject(deliveryTag, true);
                log.info("消息处理失败，deliveryTag: {}", deliveryTag);
            } catch (IOException ex) {
                log.info("拒绝消息失败，deliveryTag: {}", deliveryTag);
            }
        }
    }
}
